#--coding:utf-8--
# @Time    : 2022/5/09 02:05
# @Author  : hakold
# @File    : mission_model.py
# @PROJECT : chatroom_game

import json
import pymongo
from model import item_model


def mongo_connect():
    #myclient = pymongo.MongoClient('mongodb+srv://hakold:52Beebee@cluster0.gy1rb.mongodb.net/xiuxian?retryWrites=true&w=majority/')
    myclient = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
    #dblist = myclient.list_database_names()
    # dblist = myclient.database_names() 
    mydb = myclient["qt_game"] #创建数据库
    #collist = mydb.list_collection_names()
    mycol = mydb["player"] #集合
    return mycol

def getplayermission(data_dict):
    # 获取当前玩家的任务信息
    data = {}
    msg = ""
    account = data_dict['account']
    mycol = mongo_connect()
    check_query = { "account" : account }
    check_doc = mycol.find(check_query)
    check_list = []
    for x in check_doc:
        check_list.append(x)
    player_data = check_list[0]
    now_mission_list = player_data['mission']['now_mission']
    main_mission = {} # 主线list
    side_mission = {} # 支线list
    for mission_dict in now_mission_list:
        # 目标info 还没写
        # mission["target_info"]= mission_config[str(mission_dict['id'])]['target_info'],
        # 奖励列表 还没写
        # reward_name = ""
        #for item_id in mission_config[str(mission_dict['id'])]['reward']:
        #    reward_name += item_config[item_id]['name']
        # mission["reward"] = reward_name
        if mission_dict['type'] == 1:
            # 主线任务
            main_mission = mission_dict
            continue
        else:
            # 支线任务
            side_mission = mission_dict
            continue
    
    del player_data["_id"]
    code = "200"
    data["main_mission"] = main_mission
    data["side_mission"] = side_mission
    data['nickname'] = player_data['nickname']
    data["type"] = "mission_get"
    data["code"] = code
    data["data"] = player_data
    data = json.dumps(data)
    return data

def mission_submit(self, data_dict):
    # 玩家提交任务
    data = {} # 初始化一个返回用的dict
    account = data_dict['account']
    mission_id = data_dict['mission_id']
    msg = ""
    if account and mission_id :
        mycol = mongo_connect()
        mission_config = json.load(open("config/mission_config.json", encoding='utf-8'))
        item_config = json.load(open("config/item_config.json", encoding='utf-8'))
        this_mission_config = mission_config[str(mission_id)]
        this_mission_target = this_mission_config['target'].split("|")
        mission_target_type = this_mission_target[0] # 目标要求的属性 (str)
        mission_target_value = this_mission_target[1] # 目标要求的值 (str)
        # 获取玩家数据
        check_query = { "account" : account }
        check_doc = mycol.find(check_query)
        check_list = []
        for x in check_doc:
            check_list.append(x)
        player_data = check_list[0] # 玩家数据
        del player_data["_id"]
        nickname = player_data['nickname']
        # 拿玩家对应属性来做判断
        if player_data[mission_target_type] >= int(mission_target_value):
            # 满足条件
            # 完结任务
            mission_index = 0
            player_mission_list = player_data['mission']
            for player_mission in player_mission_list['now_mission']:
                if player_mission['id'] == mission_id:
                    # 匹配到当前任务
                    player_mission_list['now_mission'][mission_index]['status'] = 1
                    player_mission_list['finish_mission'].append(player_mission_list['now_mission'][mission_index]) # 将任务添加到已完成
                     # 判断是否增加后续任务
                    if 'subsequent_task' in mission_config[str(mission_id)]:
                    # 有后续任务
                        mission_subsequent_task = mission_config[str(mission_id)]['subsequent_task'] # 后续任务,此处拿到的是后续任务的id (int)
                        # 新增任务的样式
                        new_task = {
                        "id": mission_subsequent_task,
                        "status": 0,
                        "type": 1
                        }
                        player_mission_list['now_mission'].pop(mission_index) # 当前任务列表删除任务
                        player_mission_list['now_mission'].append(new_task) # 增加到now_mission的list当中
                        # 获得奖励（没有道具表，先不做）
                        mission_reward_pools = this_mission_config['reward']
                        show_reward_pools = []
                        show_reward_msg = ""
                        for reward_item_id in mission_reward_pools:
                            # 遍历奖品
                            # reward_item_id 是 物品id
                             # 把id加入到玩家背包里
                            show_reward_pools.append(reward_item_id)
                            item_model.bag_add_item(account, reward_item_id, 1)
                        # 增加完成
                        for reward_item_id in show_reward_pools:
                            show_reward_msg += item_config[str(reward_item_id)]['name'] + " "
                        reward_data = {}
                        reward_data['message'] = "获得任务奖励:" + "【" +show_reward_msg + "】"
                        reward_data["type"] = "mission_reward"
                        reward_data = json.dumps(reward_data)
                        self.data_send_to_user(reward_data,account)
                    else:
                    # 无后续任务
                        pass
                    newvalues = { "$set": { "mission": player_mission_list } }
                    mycol.update_one({ "account" : player_data["account"] }, newvalues)
                    print("用户" + player_data["account"] +"任务完成")
                    code = "200"
                    msg = "任务完成"
                    
                mission_index += 1
        else:
            # 未完成任务
            code = "500"
            msg = "未达到条件"

    data["type"] = "submit_main_mission"
    data["code"] = code
    data['nickname'] = nickname
    data["msg"] = msg
    data = json.dumps(data)
    return data

